package com.ys.service.base.impl;

import java.util.Map;

import com.ys.entity.storage.TccLogisticsMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.base.TbCountry;
import com.ys.mapper.base.TbCountryMapper;
import com.ys.service.base.TbCountryService;
import com.ys.vo.R;

@Service("tbCountryService")
public class TbCountryServiceImpl implements TbCountryService {

	@Autowired
	private TbCountryMapper tbCountryMapper;

	/*
	 * 新增
	 */
	@Override
	public R add(Map<String, Object> params) throws Exception {
		
		TbCountry entity = JSON.parseObject(JSON.toJSONString(params), TbCountry.class);
		
		String code = entity.getCode();
		if (code == null || code.length() == 0) {
			return R.error("地区编码不能为空");
		} else if (new TbCountry().setCode(code).count() > 0) {
			return R.error("地区编码已存在");
		}

		entity.setWlStatus(1);
		tbCountryMapper.insert(entity);
		return R.ok(AddDto.closeAndReload());
	}
	
	@Override
	@Transactional
	public R edit(Map<String, Object> params) throws Exception {
		TbCountry entity = JSON.parseObject(JSON.toJSONString(params), TbCountry.class);
		
		String code = entity.getCode();
		if (code == null || code.length() == 0) {
			return R.error("地区编码不能为空");
		} else if (new TbCountry().setCode(code).where("A.Id != " + entity.getId()).count() > 0) {
			return R.error("地区编码已存在");
		}
		//物流服务停用(需判定物流服务维护是否启用?)
		if (entity.getWlStatus() == 0){
			Integer count = new TccLogisticsMethod().setDestinationCountryCode(code).setStatus(1).count();
			if (count != 0){
				return R.error("该国家信息存在物流服务维护使用中,不允许停用!");
			}
		}

		tbCountryMapper.update(entity);
		return R.ok(EditDto.closeAndReload());
	}
}
